package cn.tedu.ivos.dict.service.impl;

import cn.tedu.ivos.base.response.PageData;
import cn.tedu.ivos.base.utils.CacheUtils;
import cn.tedu.ivos.dict.mapper.DictMapper;
import cn.tedu.ivos.dict.pojo.dto.DictSaveParam;
import cn.tedu.ivos.dict.pojo.dto.DictQuery;
import cn.tedu.ivos.dict.pojo.entity.Dict;
import cn.tedu.ivos.dict.pojo.vo.DictVO;
import cn.tedu.ivos.dict.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictServiceImpl implements DictService {
    @Autowired
    DictMapper dictMapper;
    @Autowired
    CacheUtils cacheUtils;

    @Override
    public PageData selectDict(DictQuery dictQuery) {
        log.debug("查询字典业务：{}", dictQuery);
        //根据条件查询当前页DictVO集合
        List<DictVO> list = dictMapper.selectDict(dictQuery);
        //准备PageData对象用来装返回给前端的数据
        PageData dictData  = new PageData();
        //向PageData对象中装存入当前页字典数据
        dictData.setList(list);
        //向PageData对象中装存入总记录数
        dictData.setTotal(dictMapper.selectDictCount(dictQuery));
        return dictData ;
    }

    @Override
    public void insertDict(DictSaveParam dictSaveParam) {
        Dict dict = new Dict();
        BeanUtils.copyProperties(dictSaveParam, dict);
        if(dictSaveParam.getId()==null){
            dict.setCreateTime(new Date());
            dictMapper.insertDict(dict);
        }else{
            dict.setUpdateTime(new Date());
            dictMapper.updateDict(dict);
        }

    }

    @Override
    public void deleteDict(Long id) {
        //同时清空redis中与该字典相关的缓存数据
        DictQuery dict = new DictQuery();
        dict.setId(id);
        List<DictVO> dictVOList = dictMapper.selectDict(dict);
        if (dictVOList.size() > 0 && dictVOList != null) {
            DictVO dictVO = dictVOList.get(0);
            //根据dict的code删除之前的redis缓存
            cacheUtils.delete("dictOption" + dictVO.getCode());
        }
        dictMapper.deleteDict(id);
    }
}
